import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Drawer, FormInstance, Popconfirm, Space, Typography} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {ModalForm, ProFormText, ProFormTextArea, ProForm, ProFormDigit, ProFormRadio} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {removePost, postList, loadPost, addPost, updatePost} from './service';
import type {PostBody, PostListItem, PostListPagination} from './data';

const {Text} = Typography;

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: PostBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updatePost({...fields}) : await addPost({...fields})
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: PostListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removePost(selectedRows.map((row) => row.postId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const PostPage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<PostListItem>();
  const [selectedRowsState, setSelectedRows] = useState<PostListItem[]>([]);

  const columns: ProColumns<PostListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {(index + 1) + (((actionRef?.current?.pageInfo?.current || 1) - 1) * (actionRef?.current?.pageInfo?.pageSize || 5))}
          </span>
        );
      },
    },
    {
      title: '岗位名称',
      dataIndex: 'postName',
      // copyable: true,
      render: (text, record, index) => (
        <Space>
          <Text copyable={{text: record.postName + ":" + record.postCode}}> {text}</Text>
        </Space>
      )
    },
    {
      title: '排序',
      dataIndex: 'postSort',
      tooltip: "越大越靠前",
      search: false,
      sorter: true,
      hideInDescriptions: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Success',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
    },

    {
      title: '岗位风险告知卡',
      // @ts-ignore
      span: 24,
      dataIndex: 'dangerNote',
      search: false,
      hideInTable: true,
      valueType: 'jsonCode'
    },
    {
      title: '岗位事故应急处置卡',
      // @ts-ignore
      span: 24,
      dataIndex: 'doTrouble',
      search: false,
      hideInTable: true,
      valueType: 'code'
    },
    {
      title: '任职条件',
      // @ts-ignore
      span: 24,
      dataIndex: 'jobRequire',
      search: false,
      hideInTable: true,
      valueType: 'code'
    },
    {
      title: '责任书',
      // @ts-ignore
      span: 24,
      dataIndex: 'letterLiability',
      search: false,
      hideInTable: true,
      valueType: 'code'
    },
    {
      title: '安全告知',
      // @ts-ignore
      span: 24,
      dataIndex: 'notification',
      search: false,
      hideInTable: true,
      valueType: 'code'
    },
    // {
    //   title: '创建时间',
    //   sorter: true,
    //   dataIndex: 'createTime',
    //   valueType: 'dateTime',
    //   search: false
    // },
    {
      title: '创建时间',
      sorter: true,
      align: 'center',
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{danger: true}}
          title={`确认删除岗位：${record.postName}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record])
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>

      ],
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);

  return (
    <PageContainer waterMarkProps={{content: ""}}>
      <ProTable<PostListItem, PostListPagination>
        headerTitle="岗位列表"
        actionRef={actionRef}
        rowKey="postId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              setEditMode(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={postList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              个岗位
            </div>
          }
        >
          <Popconfirm
            key="delete"
            title={`确认删除选中的${selectedRowsState.length}个岗位?`}
            okButtonProps={{danger: true}}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}
      <ModalForm<PostBody>
        title={currentRow?.postId || 0 > 0 ? "编辑岗位" : "新建岗位"}
        // width="400px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}

        onFinish={async (value) => {
          const success = await handleAdd(value, editMode);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        request={(params) => {
          if (params.postId > 0) {
            return loadPost(params).then(({data}) => {
              return data;
            });
          } else {
            return new Promise<PostBody>((resolve, reject) => {
              resolve({
                postId: 0,
                postName: "",
                postSort: 0,
                status: "0",
                dangerNote: "",
                doTrouble: "",
                jobRequire: "",
                letterLiability: "",
                notification: "",
                createTime: "",
              })
            })
          }
        }}
        params={{...currentRow}}
      >
        <ProFormText hidden name="postId"/>
        <ProForm.Group>
          <ProFormText
            rules={[
              {
                required: true,
                message: '岗位名称为必填项',
              },
            ]}
            label={"岗位名称"}
            name="postName"
            width={"lg"}
          />
          <ProFormDigit
            tooltip={"越大越靠前"}
            rules={[
              {
                required: true,
                message: '排序不能为空',
              },
            ]}
            width={"xs"}
            label={"排序"}
            name="postSort"
          />
          <ProFormRadio.Group
            name="status"
            label="状态"
            options={[
              {
                label: '启用',
                value: '0',
              },
              {
                label: '禁用',
                value: '1',
              },
            ]}
          />
        </ProForm.Group>

        <ProFormTextArea label={"岗位风险告知卡"} name="dangerNote"/>
        <ProFormTextArea label={"岗位事故应急处置卡"} name="doTrouble"/>
        <ProFormTextArea label={"任职条件"} name="jobRequire"/>
        <ProFormTextArea label={"责任书"} name="letterLiability"/>
        <ProFormTextArea label={"安全告知"} name="notification"/>
      </ModalForm>


      <Drawer
        width={800}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.postName && (
          <ProDescriptions<PostBody>
            column={2}
            bordered={true}
            title={currentRow?.postName}
            request={loadPost}
            layout={'vertical'}
            params={currentRow}
            columns={columns as ProDescriptionsItemProps<PostBody>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default PostPage;
